export default class Draw {
  constructor(para) {
    this.canvas = para.el
    if (!this.canvas) {
      return
    }
    this.canvas.width = para.width
    this.canvas.height = para.height
    this.signCallback = para.callback
    this.ctx = this.canvas.getContext('2d')
    this.stageInfo = this.canvas.getBoundingClientRect()
    this.path = {
      beginX: 0,
      beginY: 0,
      endX: 0,
      endY: 0
    }
  }

  static preHandler(e) {
    if (e.preventDefault) {
      e.preventDefault()
    } else {
      e.returnValue = false
    }
  }

  init() {
    if (!this.canvas) {
      return
    }
    this.canvas.addEventListener(
      'touchstart',
      event => {
        document.addEventListener('touchstart', this.preHandler, {
          passive: false
        })
        this.drawBegin(event)
      },
      {
        passive: false
      }
    )
    this.canvas.addEventListener(
      'touchend',
      event => {
        document.addEventListener('touchend', this.preHandler, {
          passive: false
        })
        this.drawEnd()
      },
      {
        passive: false
      }
    )
    this.clear()
  }

  drawBegin(e) {
    window.getSelection() ? window.getSelection().removeAllRanges() : document.selection.empty()
    this.ctx.strokeStyle = '#000'
    this.ctx.beginPath()
    this.ctx.moveTo(e.changedTouches[0].clientX - this.stageInfo.left, e.changedTouches[0].clientY - this.stageInfo.top)
    this.path.beginX = e.changedTouches[0].clientX - this.stageInfo.left
    this.path.beginY = e.changedTouches[0].clientY - this.stageInfo.top
    this.canvas.addEventListener(
      'touchmove',
      () => {
        this.drawing(event)
      },
      {
        passive: false
      }
    )
  }

  drawing(e) {
    this.ctx.lineTo(e.changedTouches[0].clientX - this.stageInfo.left, e.changedTouches[0].clientY - this.stageInfo.top)
    this.path.endX = e.changedTouches[0].clientX - this.stageInfo.left
    this.path.endY = e.changedTouches[0].clientY - this.stageInfo.top
    this.ctx.stroke()
  }

  isBlank() {
    const blank = document.createElement('canvas')
    blank.width = this.canvas.width
    blank.height = this.canvas.height
    return this.canvas.toDataURL() == blank.toDataURL()
  }

  drawEnd() {
    this.signCallback && this.signCallback(this.save())
    document.removeEventListener('touchstart', this.preHandler, false)
    document.removeEventListener('touchend', this.preHandler, false)
    document.removeEventListener('touchmove', this.preHandler, false)
  }

  clear() {
    this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
  }

  save() {
    return this.canvas.toDataURL('image/png')
  }
}
